package com.hrt.util;

import java.util.List;

import javax.annotation.Resource;
import javax.annotation.Resources;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.hrt.base.BaseDaoImpl;
import com.hrt.bean.Sequence;

@Repository
public class GenarateDaoImpl extends BaseDaoImpl<Sequence> implements
		CodeGenarateDao {

	/**
	 * 
	 * @param entityName
	 * @return
	 */
	public  synchronized Sequence queryMaxId(String entityName) {
		Long maxId = 0l;
		String hql = "from Sequence seq where seq.tableName='" + entityName
				+ "'";
		List list = this.getHibernateTemplate().find(hql);
		if (list != null && !list.isEmpty()) {
			Sequence seq = (Sequence) list.get(0);

			return seq;
		}
		return null;

	}

	/**
	 * 
	 * @param seq
	 */

	public  synchronized void updateMaxId(Sequence seq) {
		// TODO Auto-generated method stub
		this.updateEntity(seq);
		System.out.println("maxId has update..");
	}

	/**
	 * 
	 * @param entityName
	 * @return
	 */
	public synchronized Sequence getNextSequence(String entityName) {
		Long nextId = 0l;
		Sequence seq = queryMaxId(entityName);
		nextId = seq.getMaxId() + 1;
		seq.setMaxId(nextId);
		updateMaxId(seq);
		return seq;
	}

}
